# -*- coding: utf-8 -*-
from MyTgApi import *
import tgateapi as api
import os
import configparser

#local config check check
if(os.path.exists("config.local.ini")):
	configfile = "config.local.ini"
else:
	configfile = "config.ini"


configins=configparser.ConfigParser()
configins.read(configfile)

#Rtnctl
INSTRSTATUS=configins['Rtnctl']['instrstatus']


class CTgateSpi(api.CTGateFtdcSpi):
	myapi=''
	def __init__(self,myapi):
		api.CTGateFtdcSpi.__init__(self)
		self.myapi=myapi
		
	def OnRspError(self, pRspInfo: 'CTGateFtdcRspInfoField', nRequestID: 'int', bIsLast: 'bool') -> "void":
		print("pRspInfo", pRspInfo.ErrorMsg)
		
	def OnRspQryTGIpAddrParam(self, pTGIpAddrParam: 'CTGateFtdcTGIpAddrParamField', pRspInfo: 'CTGateFtdcRspInfoField', nRequestID: 'int', bIsLast: 'bool') -> "void":
		if(pTGIpAddrParam == None):
			print("tgate信息查询失败，请检查brokerid与userid正确性，以及appid的有效性。")
		else:
			currlist = [pTGIpAddrParam.BrokerID,\
				pTGIpAddrParam.UserID,\
				pTGIpAddrParam.Address,\
				pTGIpAddrParam.DRIdentityID,\
				pTGIpAddrParam.DRIdentityName,\
				pTGIpAddrParam.AddrSrvMode,\
				pTGIpAddrParam.AddrVer,\
				pTGIpAddrParam.AddrNo,\
				pTGIpAddrParam.AddrName,\
				pTGIpAddrParam.IsSM,\
				pTGIpAddrParam.IsLocalAddr,\
				pTGIpAddrParam.Remark,\
				pTGIpAddrParam.Site,\
				pTGIpAddrParam.NetOperator]
			self.myapi.ReqTgateInfoData.append(currlist)

		if(bIsLast == True):
			self.myapi.ctlevent.set()




#static function

#deal with too max float
def DealTooMax(mdlist):
	maxprice = 1e+15
	minprice = -1e+15
	for i in range(len(mdlist)):
		if((type(mdlist[i]) is not str) and (mdlist[i] > maxprice or mdlist[i] < minprice)):
			mdlist[i] = 0
		elif(type(mdlist[i]) is float):
			mdlist[i] = round(mdlist[i], 6)
		elif(mdlist[i] is None or mdlist[i] == ""):
			mdlist[i] = "NULL"
		else:
			mdlist[i] = mdlist[i]

#print errormsg
def PrintReMsg(pRspInfo):
	if pRspInfo is not None:
		remsg = "ErrorID= " + str(pRspInfo.ErrorID) + " ErrorMsg= " + str(pRspInfo.ErrorMsg)
		print(remsg)
	else:
		print("ErrorID= null ErrorMsg= null")
		return 1

#print func name
def PrintReName(rename):
	remsg = "receive" + rename
	print(remsg)